import React from 'react'
import {Form, Button, DatePicker, Icon, Input} from 'antd'
import moment from 'moment'
import ProcessBar from './ProcessBar'

const FormItem = Form.Item
const RangePicker = DatePicker.RangePicker

class Sale extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      dateArr: [],
      channelGoodsSaleInfoId: '',
      initDateArr: '',
      maxQuantity: '',
      minPremium: ''
    }
    // 设置不可选的日期
    this.disabledStartDate = this.disabledStartDate.bind(this)
  }
  componentDidMount () {
    let {promotionData} = this.props
    this.initSaleData(promotionData)
    this.setState({promotionData})
  }
  componentWillReceiveProps (nextProps) {
    let {promotionData} = nextProps
    this.initSaleData(promotionData)
  }
  initSaleData (promotionData) {
    // 编辑进来初始化各个控件的值
    if (promotionData && promotionData.channelGoodsSaleInfoDTO) {
      // 签约时间的开始和结束日期。
      let {agreementStartDateStr, agreementEndDateStr} = promotionData
      let {channelGoodsSaleInfoId} = promotionData.channelGoodsSaleInfoDTO
      let {maxQuantity, minPremium} = promotionData.channelGoodsSaleInfoDTO
      this.setState({
        promotionData,
        maxQuantity,
        minPremium,
        channelGoodsSaleInfoId
      })
      // 设置日期
      this.setDate(agreementStartDateStr, agreementEndDateStr)
    }
  }
  setDate (start, end) {
    let dateFormat = 'YYYY-MM-DD'
    console.log('setDate', start)
    if (start && end) {
      let initDateArr = [moment(start, dateFormat), moment(end, dateFormat)]
      this.setState({initDateArr})
    }
  }

  // 提交数据
  handleSubmit (e, btnType) {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (err) return
      let {promotionData, dateArr} = this.state
      let {maxQuantity, minPremium} = values
      if (maxQuantity <= 0 || minPremium <= 0) {
        return T.showError('Invalid number')
      }

      if (maxQuantity.indexOf('.') !== -1) return T.showError('Invalid max quantity number')
      let data = {}
      // 第三步的已经提交过的channelGoodsSaleInfoId
      if (promotionData && promotionData.channelGoodsSaleInfoDTO) {
        if (dateArr.length === 2) {
          promotionData.channelGoodsSaleInfoDTO.onlinePeriodStart = dateArr[0]
          promotionData.channelGoodsSaleInfoDTO.onlinePeriodEnd = dateArr[1]
        }
        promotionData.channelGoodsSaleInfoDTO.maxQuantity = maxQuantity
        promotionData.channelGoodsSaleInfoDTO.minPremium = minPremium

        data = Object.assign({}, promotionData, {
          btnType,
          fromStep: 3
        })
      } else {
        let onlinePeriodStart = ''
        let onlinePeriodEnd = ''
        if (dateArr[1] - dateArr[0] > 0) {
          onlinePeriodStart = dateArr[0]
          onlinePeriodEnd = dateArr[1]
        } else {
          onlinePeriodStart = dateArr[1]
          onlinePeriodEnd = dateArr[0]
        }
        let channelGoodsSaleInfoDTO = {
          onlinePeriodStart,
          onlinePeriodEnd,
          maxQuantity,
          minPremium
        }
        data = Object.assign({}, {channelGoodsSaleInfoDTO: channelGoodsSaleInfoDTO}, promotionData, {
          fromStep: 3,
          btnType
        })
      }
      if (btnType === 'publish') {
        data.operation = 1
      }
      this.props.save(data)
    })
  }
  disabledStartDate (value) {
    let promotionData = this.props.promotionData || this.state.promotionData
    let strStart
    let strEnd
    let todatay = new Date().getTime()
    if (promotionData && promotionData.agreementEndDateStr) {
      let {agreementEndDateStr: end, agreementStartDateStr: start} = promotionData
      strStart = new Date(start).getTime()

      if (todatay - strStart > 0) {
        strStart = todatay
      }
      strStart -= 24 * 60 * 60 * 1000
      strEnd = new Date(end).getTime()
      if (todatay - strEnd > 0) {
        strEnd = todatay
      }
    }
    return value <= strStart || strEnd <= value
  }
  selecteDate (dateArr) {
    let arr = dateArr.map((item) => {
      item = new Date(new Date(item).toLocaleDateString()).getTime()
      return item
    })
    this.setState({
      dateArr: arr
    })
  }

  render () {
    let {maxQuantity, minPremium, initDateArr} = this.state
    let operation = T.urlQuery('operation') || ''
    let {getFieldDecorator} = this.props.form
    let formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 }
    }
    console.log('initDateArr', initDateArr)
    let {promotionData, saleCompleteStaus, basicCompleteStaus, serviceCompleteStaus, tab} = this.props
    if (promotionData && promotionData.channelGoodsSaleInfoDTO) {
      let {channelGoodsSaleInfoDTO: sale} = promotionData
      maxQuantity = sale.maxQuantity
      minPremium = sale.minPremium
    }
    // 重新发布时候日期必须是重新选择
    if (operation === 'republish') {
      initDateArr = []
    }
    return <div className='mt16 sale-info'>
      <div >
        {/* 进度条 */}
        <ProcessBar
          tab={tab}
          save={() => this.handleSubmit(null, 'save')}
          showPreview={this.props.showPreview}
          serviceCompleteStaus={serviceCompleteStaus}
          saleCompleteStaus={saleCompleteStaus}
          basicCompleteStaus={basicCompleteStaus} />
      </div>

      <div className='f16 strong mb10 process-sub-title'>
        Sale Information
      </div>
      <Form>
        {/* <FormItem {...formItemLayout} label={'Promotion Channel'}>
          Grab
        </FormItem> */}
        <FormItem {...formItemLayout} label={'Online Period'}>
          {
          getFieldDecorator('onlineTime', {
            initialValue: initDateArr || '',
            rules: [{required: true}]
          })(
            <RangePicker
              disabledDate={this.disabledStartDate}
              onChange={(e, dateArr) => {
                this.selecteDate(dateArr)
              }}
             />)
        }
        </FormItem>
        <FormItem {...formItemLayout} label={'Max Quantity'}>
          {
          getFieldDecorator('maxQuantity', {
            initialValue: maxQuantity || '',
            rules: [{
              required: true,
              message: 'Max quantity is required'
            }]
          })(
            <Input
              type='number'
              style={{'width': '328px'}} />)
        }
        </FormItem>
        <FormItem {...formItemLayout} label={'Min Premium'}>
          {
          getFieldDecorator('minPremium', {
            initialValue: minPremium || '',
            rules: [{
              required: true,
              message: 'Min premium is required'
            }]
          })(
            <Input type='number' style={{'width': '328px'}} />)
        }
        </FormItem>
      </Form>
      <div style={{
        'marginLeft': '152px'
      }}>
        <Button
          onClick={(e) => {
            this.handleSubmit(e, 'publish')
          }}
          type='primary'>{operation || 'Publish'}</Button>
      </div>
    </div>
  }
}

export default Form.create()(Sale)
